// websocket-factory.js - 工厂函数
import { UniAppWebSocketAdapter } from './websocket-adapters.js';
import { WebWebSocketAdapter } from './websocket-adapters.js';
import appConfig from '@/config/appConfig.js';

const WS_CONFIG = {
	// url: 'ws://192.168.4.30:9235/websocket/testApp1/testFanId1',
	baseUrl: appConfig.env.GZ_WS_BASE_URL,
	options: {
		heartBeatInterval: 20000
	}
}

/**
 * 创建WebSocket实例
 * @param {string} url WebSocket地址
 * @param {Object} options 配置选项
 * @returns {WebSocketCore} WebSocket实例
 */
export function createWebSocket(url, options = WS_CONFIG.options) {
  if (typeof uni !== 'undefined') {	// UniApp环境
    return new UniAppWebSocketAdapter(WS_CONFIG.baseUrl + url, options);
  } else if (typeof WebSocket !== 'undefined') {	// Web环境
    return new WebWebSocketAdapter(WS_CONFIG.baseUrl + url, options);
  } else {	// 其他环境
    throw new Error('不支持的平台：没有找到WebSocket实现');
  }
}

// 或者导出为默认
export default createWebSocket;


/**
 * 使用示例 web
import { createWebSocket } from './websocket-factory.js';

const socket = createWebSocket('wss://echo.websocket.org', {
  reconnectMax: 5,
  heartBeatInterval: 15000
});

socket.onOpen(() => {
  console.log('WebSocket connected');
  socket.send('Hello WebSocket!');
});

socket.onMessage(data => {
  console.log('Received message:', data);
});

socket.connect();

// 断开连接测试
setTimeout(() => {
  socket.close(3000); // 模拟断开
}, 10000);

// 重新连接
setTimeout(() => {
  socket.connect();
}, 15000);
 */

/**
 * 使用示例 uniapp
<script setup>
import { onMounted, onUnmounted } from 'vue';
import { createWebSocket } from '@/utils/websocket-factory.js';

// 创建WebSocket实例
const socket = createWebSocket('wss://your-websocket-server.com', {
  reconnectMax: 3,
  heartBeatInterval: 20000
});

// 消息处理器
const handleMessage = (data) => {
  console.log('Received message:', data);
  
  if (data.type === 'notification') {
    uni.showToast({
      title: data.content,
      icon: 'none'
    });
  }
};

onMounted(() => {
  // 添加事件监听
  socket.onOpen(() => {
    console.log('WebSocket connected');
    
    // 发送认证消息
    socket.send({ 
      type: 'auth', 
      token: 'user-auth-token' 
    });
  });
  
  socket.onMessage(handleMessage);
  
  socket.onClose(() => {
    console.log('WebSocket connection closed');
    uni.showToast({
      title: '连接已断开',
      icon: 'none'
    });
  });
  
  socket.onError((err) => {
    console.error('WebSocket error:', err);
    uni.showToast({
      title: '连接错误',
      icon: 'error'
    });
  });
  
  // 连接WebSocket
  socket.connect();
});

onUnmounted(() => {
  // 清理资源
  socket.removeAllListeners();
  socket.close();
});

// 发送消息
const sendChatMessage = () => {
  socket.send({
    type: 'chat',
    content: 'Hello from UniApp!',
    timestamp: Date.now()
  });
};
</script>
<template>
  <view class="container">
    <button @click="sendChatMessage">发送消息</button>
    <button @click="socket.reconnect">重新连接</button>
  </view>
</template>
 */